package com.tt.mybatis;

import com.tt.hotkey.idgen.YitIdHelper;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class MyBatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = invocation.getArgs()[1];

        // 获取SQL操作类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();

        if (parameter == null) {
            return invocation.proceed();
        }

        // 获取参数对象的类
        Class<?> parameterClass = parameter.getClass();

        try {
            // 插入操作时自动填充创建时间和更新时间
            if (SqlCommandType.INSERT == sqlCommandType) {
                setFieldValueIfNull(parameterClass, parameter, "id", YitIdHelper.nextId());
                setFieldValueIfNull(parameterClass, parameter, "createTime", new Date());
            }

            // 更新操作时自动填充更新时间
            if (SqlCommandType.UPDATE == sqlCommandType) {
                setFieldValueIfNull(parameterClass, parameter, "updateTime", new Date());
            }
        } catch (Exception e) {
            // 异常处理，可以选择忽略或记录日志
            e.printStackTrace();
        }

        return invocation.proceed();
    }

    /**
     * 仅当字段值为null时才设置值
     */
    private void setFieldValueIfNull(Class<?> clazz, Object object, String fieldName, Object value)
            throws NoSuchFieldException, IllegalAccessException {
        Field field = getDeclaredField(clazz, fieldName);
        if (field != null) {
            field.setAccessible(true);
            // 检查当前值是否为null
            Object currentValue = field.get(object);
            if (currentValue == null) {
                field.set(object, value);
            }
        }
    }

    private Field getDeclaredField(Class<?> clazz, String fieldName) {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            // 如果当前类没有该字段，检查父类
            Class<?> superClass = clazz.getSuperclass();
            if (superClass != null) {
                return getDeclaredField(superClass, fieldName);
            }
        }
        return null;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
    @Override
    public void setProperties(Properties properties) {
        // 可以读取配置属性
    }
}
